// minepackage/pages/goodsaddress/goodsaddress.js
import Dialog from '@vant/weapp/dialog/dialog'
import Toast from '@vant/weapp/toast/toast'
import { getGoodsAddressList, delGoodsAddress, editDefaultAddress } from '../../api/goodsAddressApi.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userJSON: null,
    checked: false,
    //屏幕总高度
    windowHeight: 0,
    //按钮高度
    butHeight: 0,
    //滚动视图高度
    scrollHeight: 0,
    //收货地址集合
    goodsAddressArr: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: '我的收货地址',
    })
    //获取屏幕高度
    const res = wx.getSystemInfoSync()
    this.setData({
      butHeight: 50,
      scrollHeight: res.windowHeight - 70
    })
  },
  /**
   * 查询该用户收货地址
   */
  getUserGoodsAddress() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    })
    const params = {
      userId: this.data.userJSON.id
    }
    getGoodsAddressList(params, res => {
      this.setData({
        goodsAddressArr: res.data
      })
    }, e => {
      console.log(e)
    })
  },

  /**
   * 删除收货地址
   */
  removeGoodsAddress(id) {
    Toast.loading({
      message: '正在删除...',
      forbidClick: true,
    })
    const params = {
      id: id
    }
    delGoodsAddress(params, res => {
      Toast(res.msg)
      //查询收货地址
      this.getUserGoodsAddress()
    }, e => {
      console.log(e)
    })
  },

  /**
   * 默认地址选择
   */
  onChange(e) {
    const id = e.target.dataset.id
    const val = e.detail
    if (val) {
      Toast.loading({
        message: '正在修改...',
        forbidClick: true,
      })
      const params = {
        id: id,
        userId: this.data.userJSON.id
      }
      //修改默认地址
      editDefaultAddress(params, res => {
        Toast(res.msg)
        //重新加载
        this.getUserGoodsAddress()
      }, e => {
        console.log(e)
      })
    }
  },

  /**
   * 修改收货地址
   */
  editClick(e) {
    const id = e.target.dataset.id
    wx.navigateTo({
      url: '/minepackage/pages/addressinfo/addressinfo?off=2&id=' + id,
    })
  },

  /**
   * 添加收货地址
   */
  addGoodsAddress() {
    wx.navigateTo({
      url: '/minepackage/pages/addressinfo/addressinfo?off=1',
    })
  },

  /**
   * 删除收货地址
   */
  delGoodsAddress(e) {
    const id = e.target.dataset.id
    Dialog.confirm({
      title: '提示',
      message: '确认删除该收货地址',
    }).then(() => {
      //删除该收货地址
      this.removeGoodsAddress(id)
    }).catch(() => {
      // on cancel
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const userDataStr = wx.getStorageSync('user_data')
    if (userDataStr == null || userDataStr == '') {
      wx.reLaunch({
        url: '/loginpackage/pages/login/login',
      })
    } else {
      this.setData({
        userJSON: JSON.parse(userDataStr)
      })
      this.getUserGoodsAddress()
    }
  },

})